<template>
    <div class="product-detail" v-if="product">
        <img :src="product.imageUrl" :alt="product.name" class="product-image" />
        <h2 class="product-name">{{ product.name }}</h2>
        <p class="product-description">{{ product.description }}</p>

        <!-- 价格和库存在一行显示 -->
        <div class="price-stock">
            <span style="margin-right: 20px;" class="product-price">价格: {{ product.price | currency }}</span>
            <span class="product-stock">库存: {{ product.stock }}</span>
        </div>

        <!-- 数量选择器、付款金额和加入购物车按钮在一行显示 -->
        <div class="purchase-section">
            <div class="quantity-selector">
                <button @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
                <span>{{ quantity }}</span>
                <button @click="increaseQuantity" :disabled="quantity >= product.stock">+</button>
            </div>
            <span class="total-price">总价: {{ (product.price * quantity) | currency }}</span>
            <button style="margin-left: 100px;" @click="addToCart(product.productId)"
                class="add-to-cart-button">加入购物车</button>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { post, get } from "../until/request";
import Swal from 'sweetalert2';

const product = ref(null); // 商品信息
const quantity = ref(1); // 初始化购买数量为 1

const userInfo = ref(null); // 用户信息

// 组件挂载时从 localStorage 中获取产品信息
onMounted(() => {
    const storedData = localStorage.getItem('login');
    if (storedData) {
        userInfo.value = JSON.parse(storedData);
    }

    // 从 localStorage 中获取产品信息
    const storedProduct = localStorage.getItem('selectedProduct');
    if (storedProduct) {
        product.value = JSON.parse(storedProduct);
    }
});

// 增加数量
function increaseQuantity() {
    if (quantity.value < product.value.stock) {
        quantity.value++;
    }
}

// 减少数量
function decreaseQuantity() {
    if (quantity.value > 1) {
        quantity.value--;
    }
}

// 调用后端API将商品加入购物车
async function addToCart(productId) {
    console.log(userInfo.value.id);
    const cartItem = {
        userId: userInfo.value.id,
        productId: productId,
        quantity: quantity.value,
        totalPrice: product.value.price * quantity.value
    };

    // 调用后端API将商品加入购物车
    await get("/user/addCart", cartItem).then((res) => {
        console.log(res);
        if (res.code === 1) {
            Swal.fire({
                title: '加入购物车成功',
                icon: 'success',
            });
        } else {
            Swal.fire({
                title: '加入购物车失败',
                icon: 'error',
            });

        }
    });
}

// 组件卸载时清除 localStorage 中的数据
onUnmounted(() => {
    localStorage.removeItem('selectedProduct');
});
</script>

<style scoped>
.product-detail {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    text-align: center;
}

.product-image {
    width: 100%;
    max-width: 400px;
    height: auto;
    border-radius: 8px;
    margin-bottom: 20px;
}

.product-name {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
}

.product-description {
    font-size: 16px;
    color: #555;
    margin-bottom: 20px;
    white-space: pre-line;
    /* 保留换行符 */
}

.price-stock {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
    font-size: 18px;
}

.purchase-section {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
}

.quantity-selector {
    display: flex;
    align-items: center;
    margin-right: 20px;
}

.quantity-selector button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 5px 10px;
    cursor: pointer;
    font-size: 16px;
    border-radius: 4px;
    margin: 0 5px;
}

.quantity-selector button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

.total-price {
    font-size: 18px;
    color: #007bff;
    margin-right: 20px;
}

.add-to-cart-button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

.add-to-cart-button:hover {
    background-color: #0056b3;
}
</style>